<?php

namespace Beerus\Modules\Store\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\store\VirtualPhoneRecord;
use Biz\model\store\VirtualPhoneUseRecord;
use Biz\service\Store\StoreBusinessService;
use Doraemon\cache\UserNick;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

/**
 * Undocumented class
 */
class VirtualPhoneUseController extends Controller
{
    const PAGE_SIZE = 20;

    const CALL_TYPE_CN_ARR = ['', '门店回拨', '用户呼叫', '短信发送', '短信接收', '呼叫拦截', '短信收发拦截'];
    const UNCONNECT_CN_ARR =
        ['', '正常通话', '黑名单拦截', '无绑定关系', '呼叫限制', '其他', '未接通'];


    public function __construct()
    {
        parent::__construct();
        //隐藏新增按钮--避免隐藏动画出现
        Admin::style('.grid-create-btn{display:none;}');
        //移除新增按钮
        // Admin::script('$('.pjax-container').attr('id','pjax-container');$('.grid-create-btn').remove();');
    }

    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();

        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = [];
        if (!empty($request_data['store_id'])) {
            $condition['store_id'] = $request_data['store_id'];
        }
        //时间区间筛选
        if (!empty($request_data['time'])) {
            //开始时间
            if (!empty($request_data['time']['start'])) {
                $condition['call_time[>=]'] = strtotime($request_data['time']['start']);
            }
            //结束时间, 最后一天
            if (!empty($request_data['time']['end'])) {
                $condition['call_time[<=]'] = strtotime($request_data['time']['end']) + 86400;
            }
        }
        //电话类型筛选
        if (!empty($request_data['type'])) {
            $condition['call_type'] = $request_data['type'];
        }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];
        //列表查询
        $lists = VirtualPhoneUseRecord::select([
            'id',
            'user_uid',
            'store_id',
            'call_time',
            'total_time',
            'call_type',
            'subs_id',
            'unconnected_status'
        ], $condition); //, 'useRecord.user_phone', 'useRecord.virtual_phone'

        $subIdPhoneMap = [];
        $total = 0;
        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = VirtualPhoneUseRecord::count($condition);

            //获取所有关系id
            $subIdArr = array_column($lists, 'subs_id');
            $subIdInfoArr = VirtualPhoneRecord::getPhoneArrBySubIdS($subIdArr);
            foreach ($subIdInfoArr as $v) {
                $subIdPhoneMap[$v['subs_id']] = $v;
            }
        }

        $store_ids = array_unique(array_column($lists,'store_id'));

        $store_basics = StoreBusinessService::GetStoreBasicByIds($store_ids);

        $store_basics_kv = array_column($store_basics,null,'id');

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $subIdPhoneMap,$store_basics_kv) { //传入参数， 避免多次遍历
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('store_id', '门店id')->placeholder('请输入门店id');
                    });

                    $filter->column(1 / 2, function ($filter) {
                        // 设置datetime类型
                        $filter->between('time', '时间')->date();
                    });

                    $filter->column(1 / 2, function ($filter) {
                        // 电话类型
                        $filter->equal('type', '电话类型')->select(['1' => '门店回拨', '2' => '用户呼叫']);
                    });


                });

                $grid->column('id', 'Id');

                $grid->column('store_name', '门店名称')->display(function () use($store_basics_kv){
                    return isset($store_basics_kv[$this->store_id]) ? $store_basics_kv[$this->store_id]['name'] : '';
                });

                $grid->column('store_id', '门店Id');

                $grid->column('user_nick', '用户昵称')->display(function () {
                    return UserNick::uid2nick($this->user_uid);
                });

                $grid->column('user_uid', '用户uid');

                $grid->column('user_phone', '真实号码')->display(function () use ($subIdPhoneMap) {
                    return $subIdPhoneMap[$this->subs_id]['user_phone'];
                });

                $grid->column('virtual_phone', '虚拟号码')->display(function () use ($subIdPhoneMap) {
                    return $subIdPhoneMap[$this->subs_id]['virtual_phone'];
                });

                $grid->column('official_phone', '门店电话')->display(function () use ($subIdPhoneMap) {
                    return $subIdPhoneMap[$this->subs_id]['official_phone'];
                });

                $grid->column('call_type', '电话类型')->display(function () {
                    return self::CALL_TYPE_CN_ARR[$this->call_type];
                });

                $grid->column('unconnected_status', '接通情况')->display(function () {
                    return self::UNCONNECT_CN_ARR[$this->unconnected_status];
                });

                $grid->column('call_time', '拨打时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->call_time);
                });
                $grid->column('total_time', '通话时长')->display(function () {
                    if ($this->total_time < 60) {
                        return $this->total_time . '秒';
                    } else {
                        return (int)($this->total_time / 60) . '分' . ($this->total_time % 60) . '秒';
                    }
                });
                $grid->disableActions();
            }
        );

        $gridList->disableCreateButton();

        return $content
            ->header('虚拟手机号使用记录')
            ->row($gridList);
    }
}
